package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.ZJCMenuDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = ZJCMenuService.class)
@Transactional
public class ZJCMenuServiceImpl implements ZJCMenuService {
    @Autowired
    private ZJCMenuDao ZJCMenuDao;

    @Override
    public List<Menu> getMenuList() {
        List<Menu> list = new ArrayList<>();
        int parentMenuId = 0;
        list = this.findMenuByParentMenuId(parentMenuId);
        return list;
    }

    @Override
    public List<Menu> getMenuListByUser(User user) {
        List<Integer>  menuIds = ZJCMenuDao.findMenuIdsByUser(user.getId());
        List<Menu> list = this.findMenuByParentMenuId(0);
        List<Menu> menuList = this.findMenuByUser(list, menuIds, new ArrayList<Menu>());
        return menuList;
    }

    public List<Menu> findMenuByParentMenuId(Integer parentMenuId){
        List<Menu> list = ZJCMenuDao.findMenuByParentMenuId(parentMenuId);
        if(list != null && list.size() > 0){
            for (Menu menu : list) {
                Integer menuId = menu.getId();
                List<Menu> childrenList = this.findMenuByParentMenuId(menuId);
                menu.setChildren(childrenList);
            }
        }
        return list;
    }

    public List<Menu> findMenuByUser(List<Menu> list ,List<Integer> ids,List<Menu> menuList){
        if(list!=null && list.size() >0 ){
            for (Menu menu : list) {
                for (Integer id : ids) {
                    if(id == menu.getId()){
                        menu.setChildren(this.findMenuByUser(menu.getChildren(),ids,new ArrayList<Menu>()));
                        menuList.add(menu);
                    }
                }
            }
        }
        return menuList;
    }
}
